package com.scoy.honeymei.activity.a_checkseaat;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.kokozu.widget.seatview.OnChooseSeatListener;
import com.kokozu.widget.seatview.SeatData;
import com.kokozu.widget.seatview.SeatThumbnailView;
import com.kokozu.widget.seatview.SeatView;
import com.lzy.okgo.model.HttpParams;
import com.scoy.honeymei.MeApp;
import com.scoy.honeymei.R;
import com.scoy.honeymei.activity.MainActivity;
import com.scoy.honeymei.activity.film.CinemaListActivity;
import com.scoy.honeymei.adapter.CheckTicketAdapter;
import com.scoy.honeymei.base.BaseActivity;
import com.scoy.honeymei.bean.CheckSeatBean;
import com.scoy.honeymei.bean.CouponBean;
import com.scoy.honeymei.bean.FilmTicketBean;
import com.scoy.honeymei.bean.SeatBean;
import com.scoy.honeymei.http.HpCallback;
import com.scoy.honeymei.http.HpGo;
import com.scoy.honeymei.url.ApiCallBack;
import com.scoy.honeymei.url.MeConstant;
import com.scoy.honeymei.url.MyUrl;
import com.scoy.honeymei.utils.IntentUtil;
import com.scoy.honeymei.utils.MyUtil;
import com.scoy.honeymei.utils.SPHelper;
import com.scoy.honeymei.utils.SystemUtil;
import com.scoy.honeymei.utils.TimeUtil;
import com.scoy.honeymei.wxapi.PayEvent;
import com.scoy.honeymei.wxapi.PayUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ClassName: SeatActivity$
 * @Description: 选座界面
 * @Author: GaoZhan
 * @CreateDate: 2019/9/5/0005$ 下午 15:57$
 * @UpdateUser: 更新者
 * @UpdateDate: 2019/9/5/0005$ 下午 15:57$
 * @UpdateRemark: 更新内容
 */
public class SeatActivity extends BaseActivity implements OnChooseSeatListener {

    @BindView(R.id.back_iv)
    ImageView backIv;
    @BindView(R.id.title_tv)
    TextView titleTv;
    @BindView(R.id.sign_tv)
    TextView signTv;
    @BindView(R.id.title_llt)
    LinearLayout titleLlt;
    @BindView(R.id.cst_name_tv)
    TextView cstNameTv;
    @BindView(R.id.cst_locate_tv)
    TextView cstLocateTv;
    @BindView(R.id.cst_ticketnum_tv)
    TextView cstTicketnumTv;
    @BindView(R.id.cst_tocheck_iv)
    ImageView cstTocheckIv;
    @BindView(R.id.cst_allmoney_tv)
    TextView cstAllmoneyTv;
    @BindView(R.id.cst_ok_tv)
    TextView cstOkTv;
    @BindView(R.id.seat_view)
    SeatView seatView;
    @BindView(R.id.thumbnail_view)
    SeatThumbnailView thumbnailView;
    @BindView(R.id.seat_check_tv)
    TextView seatCheckTv;
    @BindView(R.id.cst_useticket_tv)
    CheckBox cstUseticketTv;
    @BindView(R.id.cst_htsign_tv)
    TextView cstHtsignTv;
    @BindView(R.id.cst_chooseticket_tv)
    TextView cstChooseticketTv;
    @BindView(R.id.cst_toticket_llt)
    LinearLayout cstToticketLlt;
    @BindView(R.id.noticket_llt)
    LinearLayout noticketLlt;
    @BindView(R.id.cst_messagefee_tv)
    TextView cstMessagefeeTv;

    @BindView(R.id.cst_messagefee_llt)
    LinearLayout cstMessagefeeLlt;

    private SeatActivity mContext;
    private Dialog dialogcheck;
    private int fId;
    private StringBuilder seatCheck;
    private ArrayList<CouponBean> datacklist;
    private int couponId;
    //优惠券减免价格
    private String reduceMoney = "0";
    //电影价格
    private String priceFilm = "0";
    //选位数量
    private int checkNum;
    //观影券总数量
    private int movieNum;
    // private String payType = "null";
    //1=支付宝、2=微信、3=观影券
    private int payType = -1;
    private double shouldNum = 0.0;
    private int checkedPosition = -1;
    private String payThree;
    private int countXz;
    private String titleXz;
    private int cinemaId;
    private boolean movieUserStatus;
    private double xxmoney;
    private String freePrice;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activy_checkseat);
        ButterKnife.bind(this);
        mContext = SeatActivity.this;
        fId = getIntent().getIntExtra("fId", 0);
        cinemaId = getIntent().getIntExtra("cinemaId", 0);

        initNormal();

        httpMovietobuy();
    }

    @Override
    public void initNormal() {

        datacklist = new ArrayList<>();

        titleTv.setText(R.string.film);
        signTv.setText("返回首页");
        signTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MeApp.getInstance().finishAllActivity();
                startActivity(new Intent(mContext, MainActivity.class));
                finish();
            }
        });
        signTv.setVisibility(View.VISIBLE);

        MyUtil.setStatusBar(mContext, getWindow(), true, R.color.colorWhite);
        titleLlt.setPadding(0, MyUtil.getStatusBarHeight(mContext), 0, 0);

        seatView.attachThumbnailView(thumbnailView);
        seatView.setOnChooseSeatListener(this);
        seatView.setSeatState(SeatView.STATE_LOADING);

        cstUseticketTv.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    noticketLlt.setVisibility(View.GONE);
                } else {
                    noticketLlt.setVisibility(View.VISIBLE);
                }
            }
        });

        EventBus.getDefault().register(this);
    }

    @OnClick({R.id.back_iv, R.id.cst_ok_tv, R.id.cst_useticket_tv, R.id.cst_toticket_llt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_iv:
                finish();
                break;
            case R.id.cst_toticket_llt:
                onCheck();
                break;
            case R.id.cst_useticket_tv:
                if (cstUseticketTv.isSelected()) {
                    cstUseticketTv.setSelected(false);
                    cstMessagefeeLlt.setVisibility(View.VISIBLE);
                    cstMessagefeeTv.setText(MessageFormat.format("¥{0}", xxmoney));
                } else {
                    cstUseticketTv.setSelected(true);
                    cstMessagefeeLlt.setVisibility(movieUserStatus ? View.GONE : View.VISIBLE);
                    cstMessagefeeTv.setText("¥" + freePrice);
                }
                break;
            case R.id.cst_ok_tv:
                if (checkNum == 0) {
                    return;
                }
                //座位规则
                if (!seatView.isSelectedSeatLegal()) {
                    MyUtil.mytoast(mContext, "请不要留空座");
                    return;
                }
                if (cstUseticketTv.isChecked()) { //使用观影券
                    if (checkNum > movieNum/movie_count) {
                        MyUtil.mytoast(mContext, "观影券数量不足，无法购买");
                        return;
                    }
//                    if (checkNum > movieNum) {
//                        MyUtil.mytoast(mContext, "观影券数量不足，无法购买");
//                        return;
//                    }
                    new AlertDialog.Builder(mContext).setTitle("确认使用观影券购买？")
                            .setPositiveButton("确认", (dialog, which) -> {
                                if (movieUserStatus) {
                                    payType = 3;
                                    httpOksure(payType, "");
                                } else {
                                    showdialog();
                                }
                            })
                            .show();

                } else { //其他购买
                    if (checkNum * Double.parseDouble(priceFilm) < shouldNum) {
                        MyUtil.mytoast(mContext, "优惠券未达到使用要求，无法使用");
                        return;
                    }
                    showdialog();
                }

                break;
            default:
                break;
        }
    }

    //seat
    @Override
    public void onPickLoverSeatOverMaxCount(int maxSelectCount) { //情侣座
    }

    @Override
    public void onSelectedSeatOverMaxCount(int maxSelectCount) {  //最大座位
        Toast.makeText(this, titleXz, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onSelectSeatNotMatchRegular() {  //规则
        Toast.makeText(this, "不能留空座", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onSelectedSeatChanged(List<SeatData> selectedSeats) {  //已选
        if (selectedSeats == null) {
            return;
        }
        StringBuilder seatShow = new StringBuilder();
        seatCheck = new StringBuilder();
        checkNum = 0;
        for (SeatData seat : selectedSeats) {
            seatCheck.append(seat.seatRow);
            seatCheck.append("|");
            seatCheck.append(seat.seatCol);
            seatCheck.append(",");

            checkNum += 1;

            seatShow.append(seat.seatRow);
            seatShow.append("排");
            seatShow.append(seat.seatCol);
            seatShow.append("座  ");
        }
        seatCheckTv.setText(seatShow);

        double allPce = checkNum * Double.parseDouble(priceFilm) - Double.parseDouble(reduceMoney);

        cstAllmoneyTv.setText(MessageFormat.format("¥{0}", MyUtil.doubleTo2String(allPce < 0 ? 0 : allPce)));
    }

    @Override
    public void onSelectedSeatSold() { //已售
        Toast.makeText(this, "选择的座位已被售出", Toast.LENGTH_SHORT).show();
    }

    private void loadSeats(List<SeatBean> seats) {
        new Thread(
                () -> {
                    if (seats != null) {
                        final List<SeatData> seatList = new ArrayList<>();
                        for (SeatBean seat : seats) {
                            String paihao = seat.getPai();
                            List<SeatBean.ZuoBean> zuo = seat.getZuo();
                            for (SeatBean.ZuoBean pai : zuo) {
                                //"stu": 0 //状态，0=未售出、1=已售出、-1=空间隔
                                //"Status": 0 //状态，0=空间隔、1=正常
                                SeatData seatData = new SeatData();
                                seatData.type = pai.getStatus() == 0 ? SeatData.TYPE_NULL : SeatData.TYPE_NORMAL;
                               /* if (pai.getStu() == -1) {
                                    seatData.state = SeatData.STATE_NULL;
                                } else*/
                                if (pai.getStu() == 1) {
                                    seatData.state = SeatData.STATE_SOLD;
                                } else {
                                    seatData.state = SeatData.STATE_NORMAL;
                                }

                                if (pai.getStatus() == 0 && pai.getStu() == 0) {
                                    seatData.state = SeatData.STATE_NULL;
                                }
                                //   seatData.state = pai.getStu() == 0 ? SeatData.STATE_NORMAL : SeatData.STATE_SOLD;

                                int lie = pai.getIndex();
                                int hang = pai.getPai();
                                seatData.point = new Point(hang, lie);
                                seatData.seatRow = pai.getPai() + "";
                                seatData.seatCol = pai.getZuohao() + "";
                                seatList.add(seatData);

                            }
                        }

                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        runOnUiThread(() -> seatView.setSeatData(seatList));
                    }

                })
                .start();

    }
    private int movie_count=0;

    private void httpMovietobuy() {
        HttpParams params = new HttpParams();
        params.put("id", fId);
        params.put("cinema_id", cinemaId);
        params.put("uid", SPHelper.getString(MeConstant.UID, ""));
        HpGo.newInstance().HttpGo(this, MyUrl.MOVIE_TOBUY, params, new ApiCallBack() {
            @Override
            public void onSuccess(String o) {
                CheckSeatBean checkSeatBean = new Gson().fromJson(o, CheckSeatBean.class);
                List<SeatBean> zuowei = checkSeatBean.getZuowei();
                CheckSeatBean.MovieBean movie = checkSeatBean.getMovie();
                cstNameTv.setText(movie.getTitle());
                cstLocateTv.setText(MessageFormat.format("{0}厅", movie.getFyt_no()));

                //返回信息增加 movie_user_status 会员卡状态:true=企业会员卡,走之前逻辑,false=免费会员卡,
                // 如观影次数(movie_user)大于0,需要走微信支付宝逻辑支付,
                movieUserStatus = checkSeatBean.isMovie_user_status();

                priceFilm = movie.getPrice();

                loadSeats(zuowei);

                payThree = checkSeatBean.getPaytype();

                movieNum = checkSeatBean.getMovie_user();
                if (movieNum == 0) {
                    cstUseticketTv.setClickable(false);
                }
                movie_count=checkSeatBean.getMovie().getMovie_count();
                if (movie_count == 0) {
                    cstUseticketTv.setClickable(false);
                }
                cstTicketnumTv.setText(MessageFormat.format("剩余{0}次", movieNum));
                xxmoney = movie.getXx_money();
                freePrice = checkSeatBean.getFree_price();

                cstMessagefeeTv.setText(MessageFormat.format("¥{0}", xxmoney));

                List<FilmTicketBean> yhq = checkSeatBean.getYhq();

                if (yhq != null && yhq.size() > 0) {
                    cstToticketLlt.setClickable(true);
                    cstHtsignTv.setTextColor(getResources().getColor(R.color.colorWhite));
                    datacklist.add(new CouponBean(0, "0.00", "0.00", "0000-00-00", "film"));
                    for (FilmTicketBean ybean : yhq) {
                        datacklist.add(new CouponBean(ybean.getId(), ybean.getMoney(), ybean.getCondition(), TimeUtil.getLongToDatePHP(ybean.getEndtime(), "yyyy-MM-dd"), "film"));
                    }
                } else {
                    cstToticketLlt.setClickable(false);
                    cstHtsignTv.setText("无可用优惠券");
                    cstHtsignTv.setTextColor(getResources().getColor(R.color.colorMainGray9));
                    cstHtsignTv.setBackgroundResource(R.drawable.shape_gray_all90);
                }

                CheckSeatBean.XianZhiBean xianzhi = checkSeatBean.getXianzhi();
                countXz = xianzhi.getCount();
                titleXz = xianzhi.getTitle();

                if (countXz != 0) {
                    seatView.setmMaxSelectedCount(countXz);
                }

            }
        });

    }

    /**
     * 选择优惠券弹窗
     */
    public void onCheck() {
        final Dialog dialogcheck = new Dialog(mContext, R.style.BottomDialogStyle);
        View view = View.inflate(mContext, R.layout.dialog_check_ticket, null);
        TextView cancleTv = view.findViewById(R.id.cts_cancle_tv);
        TextView sureTv = view.findViewById(R.id.cts_sure_tv);
        RecyclerView dialogRv = view.findViewById(R.id.cts_rv);


        CheckTicketAdapter checkTicketAdapter = new CheckTicketAdapter(mContext, datacklist);
        dialogRv.setLayoutManager(new LinearLayoutManager(mContext, RecyclerView.VERTICAL, false));
        DividerItemDecoration did = new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL);
        did.setDrawable(getResources().getDrawable(R.drawable.divider_gray_line_pd));
        dialogRv.setAdapter(checkTicketAdapter);

        if (checkedPosition != -1) {
            checkTicketAdapter.setCheckedPosition(checkedPosition);
        }

        dialogcheck.setContentView(view);
        dialogcheck.setCanceledOnTouchOutside(true);
        Window dialogWindow = dialogcheck.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (SystemUtil.getScreenWidth(mContext));
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.BOTTOM;
        dialogWindow.setAttributes(lp);
        cancleTv.setOnClickListener(v -> dialogcheck.dismiss());

        sureTv.setOnClickListener(v -> {
            dialogcheck.dismiss();
            cstHtsignTv.setVisibility(View.GONE);

            checkedPosition = checkTicketAdapter.getCheckedPosition();
            if (checkedPosition != -1) {
                CouponBean couponBean = datacklist.get(checkedPosition);
                if (checkedPosition == 0) {
                    couponId = 0;
                    reduceMoney = "0";
                    shouldNum = 0.0;
                    cstChooseticketTv.setText("-¥0.00");
                } else {
                    couponId = couponBean.getId();
                    reduceMoney = couponBean.getMoney();
                    cstChooseticketTv.setText("-¥" + couponBean.getMoney());
                    shouldNum = Double.parseDouble(couponBean.getCondition());
                }
            } else {
                couponId = 0;
                reduceMoney = "0";
                shouldNum = 0.0;
                cstChooseticketTv.setText("-¥0.00");
            }

            double allPce = checkNum * Double.parseDouble(priceFilm) - Double.parseDouble(reduceMoney);

            cstAllmoneyTv.setText(MessageFormat.format("¥{0}", MyUtil.doubleTo2String(allPce < 0 ? 0 : allPce)));
        });

        dialogcheck.show();
    }

    /**
     * 选择弹窗
     */
    private void showdialog() {
        final Dialog dialogpay = new Dialog(this, R.style.BottomDialogStyle);
        View view = View.inflate(this, R.layout.dialog_tocheckpay, null);

        ImageView imgClose = view.findViewById(R.id.imgClose);
        Button btnSure = view.findViewById(R.id.btnSure);
        TextView alipayTv = view.findViewById(R.id.txtZhifubao);
        TextView wxpayTv = view.findViewById(R.id.txtWechat);
        //     TextView walletTv = view.findViewById(R.id.txtWallet);

        dialogpay.setOnDismissListener(dialog -> payType = -1);

        imgClose.setOnClickListener(view12 -> dialogpay.dismiss());
        alipayTv.setOnClickListener(v -> {
            alipayTv.setSelected(true);
            wxpayTv.setSelected(false);
            //    walletTv.setSelected(false);
            payType = 1;
        });
        wxpayTv.setOnClickListener(v -> {
            alipayTv.setSelected(false);
            wxpayTv.setSelected(true);
            //  walletTv.setSelected(false);
            payType = 2;
        });


        btnSure.setOnClickListener(view1 -> {
            if (/*!"null".equals(payType)*/payType != -1) {
                httpOksure(payType, payThree);
                dialogpay.dismiss();
            }
        });

        dialogpay.setContentView(view);
        dialogpay.setCanceledOnTouchOutside(true);
        Window dialogWindow = dialogpay.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (SystemUtil.getScreenWidth(mContext));
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.BOTTOM;
        dialogWindow.setAttributes(lp);
        dialogpay.show();

    }


    private void httpOksure(int payType, String payThree) {
        HttpParams params = new HttpParams();
        params.put("id", fId);
        params.put("cinema_id", cinemaId);
        //使用免费观影次数
        params.put("use_user_count", cstUseticketTv.isChecked()?1:0);
        params.put("uid", SPHelper.getString(MeConstant.UID, ""));
        params.put("zuowei", seatCheck.toString());
        params.put("yhq_id", cstUseticketTv.isSelected() ? 0 : couponId);
        params.put("pay_type", payType);
        HpGo.newInstance().HttpGo(this, MyUrl.MOVIE_CREATEORDER, params, new ApiCallBack() {
            @Override
            public void onSuccess(String o) {

                if (payType == 3) {
                    MyUtil.mytoast0(mContext, "支付成功", R.mipmap.ic_sure);
                    setResult(0x871);
                    finish();
                } else {
                    // payThree  1  三方； 2  原生
                    if ("2".equals(payThree)) {
                        if ("false".equals(o)) {
                            MyUtil.mytoast(mContext, "支付错误");
                            return;
                        }
                        PayUtil.toPayPayPay(mContext, payType, o);//支付

                    } else {
                        if (payType == 1) {
                            IntentUtil.openAPP(mContext, MyUrl.APP_OPEN_ALIPAY + o);
                            finish();
                        } else {
                            if ("false".equals(o)) {
                                MyUtil.mytoast(mContext, "支付错误");
                                return;
                            }
                            PayUtil.toPayPayPay(mContext, payType, o);//支付
                        }
                    }
                }
            }

        });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPayEvent(PayEvent event) {
        Log.d("WXPAY", "--------onPayFinish 00, errCode = " + event.toString());
        int type = event.getType();//0 成功 -1失败 -2取消
        if (type == 0) {
            MyUtil.mytoast0(mContext, "支付成功", R.mipmap.ic_sure);
            setResult(0x871);
            finish();
        } else if (type == -1) {
            MyUtil.mytoast(mContext, "支付失败");
        } else {
            MyUtil.mytoast(mContext, "支付取消");
        }

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
